package com.itheima.kafka.simple;

import org.apache.kafka.clients.producer.Callback;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;

import java.util.Properties;
import java.util.concurrent.Future;

/**
 * @Description:
 * @Version: V1.0
 */
public class ProducerFastStart {

    private static final String TOPIC = "lijianbin-kafka";

    public static void main(String[] args) throws Exception {

        //添加kafka的配置信息
        Properties properties = new Properties();
        //配置broker信息
        properties.put("bootstrap.servers","121.40.57.228:9092");
        // key value 序列化 String
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");
        // 重试次数
        properties.put(ProducerConfig.RETRIES_CONFIG,10);

        //生产者对象
        KafkaProducer<String,String> producer = new KafkaProducer<String, String>(properties);
        ProducerRecord<String, String> record = new ProducerRecord<String, String>(TOPIC, "00001", "hello kafka");
        Future<RecordMetadata> message = producer.send(record);
        System.out.println("message = " + message);
//        //封装消息
//        for (int i = 0; i < 10; i++) {
//            ProducerRecord<String,String> record = new ProducerRecord<String, String>(TOPIC,"00001"+i,"hello kafka"+i);
////            Future<RecordMetadata> future = producer.send(record);
////            System.out.println(future.get().offset());
////            System.out.println(future.get().partition());
//
//
//            //异步发送消息
//            try {
//                producer.send(record, new Callback() {
//                    @Override
//                    public void onCompletion(RecordMetadata recordMetadata, Exception e) {
//                        if(e!=null){
//                            e.printStackTrace();
//                        }
//                        System.out.println(recordMetadata.offset());
//                    }
//                });
//            }catch (Exception e){
//                e.printStackTrace();
//            }
//        }


        producer.close();
    }
}
